package com.taoge.p4.common.interceptor;


import com.taoge.p4.common.annotation.NotSign;
import com.taoge.p4.common.constants.GlobalConstants;
import com.taoge.p4.common.constants.SysUserContext;
import com.taoge.p4.common.constants.SysUserInfo;
import com.taoge.p4.common.constants.UserContext;
import com.taoge.p4.common.exception.TokenException;
import com.taoge.p4.common.utils.CookieUtil;
import com.taoge.p4.common.utils.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.method.HandlerMethod;

@Configuration
public class SysInterceptor extends BaseInterceptor {
    @Override
    void validateToken(HttpServletRequest request, HandlerMethod handlerMethod) {
        NotSign notSign = AnnotationUtils.findAnnotation(
                handlerMethod.getMethod(),
                NotSign.class
        );
        if (notSign != null) {
            return;
        }

        String sysToken = CookieUtil.getCookieByName(request, GlobalConstants.SYS_TOKEN);
        if (sysToken == null) {
            throw new TokenException("请登录后再操作");
        }

        // 解密token，得到管理员用户id
        Long userId = TokenUtil.parseToken(sysToken);
        SysUserInfo sysUserInfo = new SysUserInfo();
        sysUserInfo.setId(userId);
        SysUserContext.set(sysUserInfo);
    }

    @Override
    void doAfterCompletion() {
        // 删除管理员ThreadLocal
        UserContext.remove();
    }
}
